package com.hardson.toolkit.swing.print;

import java.awt.Graphics;
import java.awt.PrintJob;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class PrintTest extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;

	PrintJob p = null;

	Graphics g = null;

	JTextArea text = new JTextArea(10, 10);

	JButton printTextFied = new JButton("打印文本框");

	JButton printFrame = new JButton("打印窗口");

	JButton printButton = new JButton("打印按钮");

	public PrintTest() {
		super("在应用程序中打印");
		this.printTextFied.addActionListener(this);
		this.printFrame.addActionListener(this);
		this.printButton.addActionListener(this);
		this.add(this.text, "Center");
		JPanel panel = new JPanel();
		panel.add(this.printTextFied);
		panel.add(this.printFrame);
		panel.add(this.printButton);
		this.add(panel, "South");
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void actionPerformed(final ActionEvent e) {

		if (e.getSource() == this.printTextFied) {
			this.p = this.getToolkit().getPrintJob(this, "ok", null);
			this.g = this.p.getGraphics(); //p获取一个用于打印的 Graphics对象
			this.g.translate(120, 200);
			this.text.printAll(this.g); //打印当前文本区及其内容
			this.g.dispose(); //释放对象 g
			this.p.end();
		} else if (e.getSource() == this.printFrame) {
			this.p = this.getToolkit().getPrintJob(this, "ok", null);
			this.g = this.p.getGraphics();
			this.g.translate(120, 200);
			this.printAll(this.g); //打印当前窗口及其子组件
			this.g.dispose();
			this.p.end();
		} else if (e.getSource() == this.printButton) {
			this.p = this.getToolkit().getPrintJob(this, "ok", null);
			this.g = this.p.getGraphics();
			this.g.translate(120, 200); //在打印页的坐标(120,200)处打印printTextFied按扭
			this.printTextFied.printAll(this.g);
			this.g.translate(78, 0); //在打印页的坐标(198,200)处打印printFrame按扭
			this.printFrame.printAll(this.g);
			this.g.translate(66, 0); //在打印页的坐标(264,200)处打印printButton”
			this.printButton.printAll(this.g);
			this.g.dispose();
			this.p.end();
		}
	}

	public static void main(final String args[]) {
		PrintTest f = new PrintTest();
		f.setBounds(70, 70, 570, 289);
		f.setVisible(true);
		f.validate();
	}
}
